package cn._51doit.flink.day02;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;

import java.util.Random;

/**
 * 如果是自定义Source，通常会继承RichParallelSourceFunction这个抽象类
 *
 * 方法调用顺序：Open(每个并行调用一次) -> Run(每个并行调用一次，无限数据源，while循环不退出) -> Cancel（如果人为停止job， 每个并行调用一次） ->  Close（每个并行调用一次）
 */
public class ParallelCustomSource2 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //可以认为设置执行环境的并行度
        //env.setParallelism(6);
        //System.out.println(env.getParallelism());

        DataStreamSource<Integer> lines = env.addSource(new ParallelMySource2());

        //lines.setParallelism(1);

        lines.print();

        env.execute();


    }

    private static class ParallelMySource2 extends RichParallelSourceFunction<Integer> {


        private boolean flag = true;

        @Override
        public void run(SourceContext<Integer> ctx) throws Exception {

            System.out.println("RUN method Invoked !!!");
            Random random = new Random();
            while (flag) {
                int i = random.nextInt();
                ctx.collect(i);
                Thread.sleep(2000);
            }
        }

        @Override
        public void cancel() {
            System.out.println("CANCEL method Invoked @@@@");
            flag = false;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("Open method Invoked ###");
        }

        @Override
        public void close() throws Exception {
            System.out.println("Close method Invoked $$$");
        }
    }


}
